//
//  KABCosAuthenticationVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/7/1.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosAuthenticationVC.h"
#import "MBProgressHUD+XDPrompt.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "KABModel.h"

@interface KABCosAuthenticationVC ()
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *idTextField;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@end

@implementation KABCosAuthenticationVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"账户实名认证";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
}

- (void)initSubViews {
    [self.nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.idTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = CGRectGetHeight(self.sureBtn.bounds) / 2.0;
    [self.sureBtn addTarget:self action:@selector(sureBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - delegate
#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sureBtnTapped:(UIButton *)btn {
    if (![self checkUserInput]) {
        return;
    }
    
    NSString *msg = [NSString stringWithFormat:@"姓名 %@\n身份证 %@", self.nameTextField.text, self.idTextField.text];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请确认实名信息，一旦认证无法修改" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self requestIdAuthentication];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSInteger maxLength = 40;
    
    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1) {
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark - private methods
- (BOOL)checkUserInput {
    if (!self.nameTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入真实姓名"];
        return NO;
    }
    
    if (!self.idTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入证件号码"];
        return NO;
    }
    
    return YES;
}

- (void)exitViewController {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.completeHandle) {
            self.completeHandle();
            self.completeHandle = nil;
        }
    }];
}

#pragma mark - network request
- (void)requestIdAuthentication {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"real_name" : self.nameTextField.text,
                           @"id_card" : self.idTextField.text};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiIdCertificate] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"实名认证返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [KABModel sharedInstance].userInfo.misc_detail.is_celebrity = YES;
            MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"实名认证成功，可以发布Cos啦"];
            temp.completionBlock = ^{
                [self exitViewController];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"实名认证失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

@end
